package fr.beasymptotic.becv.client;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

public class CVBuilder implements CVConstants{
	private CVBuilder() {};
	
	public static CV build(String CVContent) {
		CV cv = new CV();
		
		Document xmlCV = XMLParser.parse(CVContent);
		PersonalDetails personalDetails = buildPersonalDetails(xmlCV);
		cv.setPersonalDetails(personalDetails);
		return cv;
	}
	
	private static PersonalDetails buildPersonalDetails(Document xmlCV) {
		Element documentElement = xmlCV.getDocumentElement();
		PersonalDetails details = new PersonalDetails();
		
		Node personalDetails = xmlCV.getElementsByTagName(PERSONAL_DETAILS).item(0);
		NodeList childNodes = personalDetails.getChildNodes();
		int length = childNodes.getLength();
		for(int i = 0 ; i < length ; i++) {
			Node item = childNodes.item(i);
			short nodeType = item.getNodeType();
			if(Node.ELEMENT_NODE == nodeType) {
				String nodeName = item.getNodeName();
				String nodeValue = item.getFirstChild().getNodeValue();
				if(nodeName.equals(FIRSTNAME)) {
					details.setFirstName(nodeValue);
				} else if(nodeName.equals(LASTNAME)) {
					details.setLastName(nodeValue);
				} else if(nodeName.equals(BIRTHDATE)) {
					details.setBirthDate(DateTimeFormat.getShortDateFormat().parse(nodeValue));
				}
			}
		}
		
		return details;
	}
}
